package org.example.filter;

import lombok.Getter;
import lombok.Setter;
import org.example.util.JwtUtils;
import org.example.validate.TokenAuthenticationConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器处理所有HTTP请求，并检查是否存在带有正确令牌的Authorization标头。例如，如果令牌未过期或签名密钥正确。
 */
public class TokenAuthorizationFilter extends BasicAuthenticationFilter {

    private static final Logger logger = LoggerFactory.getLogger(TokenAuthorizationFilter.class);

    public TokenAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Setter
    @Getter
    private JwtUtils jwtUtils;

//    @Setter
//    @Getter
//    private SecurityProperties properties;

    @Setter
    @Getter
    private TokenAuthenticationConverter tokenAuthenticationConverter;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        Authentication convert = tokenAuthenticationConverter.convert(request);
//        String authorization = request.getHeader(properties.getTokenHeader());
        // 如果请求头中没有token信息则直接放行了
        if (convert == null) {
            chain.doFilter(request, response);
            return;
        }

        // 如果请求头中有token，则进行解析，并且设置授权信息
        SecurityContextHolder.getContext().setAuthentication(convert);

//        Date expiration = jwtUtils.getTokenBody(authorization).getExpiration();
//        //判断是否需要刷新token,30分钟内的需要
//        Boolean needRefreshToken = jwtUtils.isNeedRefreshToken(expiration, 30);
//        response.addHeader(properties.getNeedRefresh(),needRefreshToken.toString());

        super.doFilter(request, response, chain);
    }

}
